package com.googlecode.wickedforms.xvergabe.modelers.components;

import java.util.Locale;

import org.apache.xmlbeans.XmlObject;
import org.xvergabe.xsd.forms.components.x20.AbstractComponent;
import org.xvergabe.xsd.forms.components.x20.AbstractField;
import org.xvergabe.xsd.forms.components.x20.RoleType;
import org.xvergabe.xsd.forms.components.x20.Section;

import com.googlecode.wickedforms.model.SectionModel;
import com.googlecode.wickedforms.xvergabe.modelers.FormModeller;
import com.googlecode.wickedforms.xvergabe.modelers.XmlModeller;
import com.googlecode.wickedforms.xvergabe.modelers.fields.AbstractFieldModeller;
import com.googlecode.wickedforms.xvergabe.types.ComponentType;
import com.googlecode.wickedforms.xvergabe.util.XMLBeansUtil;

public class SectionModeller implements XmlModeller<Section, SectionModel> {

	AbstractComponentModeller abstractComponentModeller;

	AbstractFieldModeller abstractFieldModeller;

	private Integer sectionIndex;

	private final FormModeller formModeller;

	/**
	 * 
	 * @param sectionIndex
	 *            the (1-based) index of the section within the form.
	 */
	public SectionModeller(FormModeller formModeller, int sectionIndex) {
		this.formModeller = formModeller;
		this.sectionIndex = sectionIndex;
	}

	public SectionModeller(FormModeller formModeller) {
		this.formModeller = formModeller;
	}

	@Override
	public SectionModel createModelFromXml(final Section xmlObject,
			final Locale locale, final RoleType.Enum sellerMode) {

		abstractComponentModeller = new AbstractComponentModeller(formModeller);
		abstractFieldModeller = new AbstractFieldModeller();

		SectionModel section = new SectionModel(
				ComponentType.SECTION.getMessage(locale));

		if (sectionIndex != null) {
			if (!xmlObject.isSetLabelled() || xmlObject.getLabelled()) {
				// default: index + label from meta data
				section.setLabel(sectionIndex
						+ ". "
						+ XMLBeansUtil.getLabel(xmlObject.getMetadata(), locale));
			} else {
				section.setLabel(sectionIndex + ".");
			}
		}

		for (XmlObject sectionElement : xmlObject.getElementArray()) {

			if (sectionElement instanceof AbstractField) {
				AbstractField component = (AbstractField) sectionElement;
				section.add(abstractFieldModeller.createModelFromXml(component,
						locale, sellerMode));
			} else if (sectionElement instanceof AbstractComponent) {
				AbstractComponent component = (AbstractComponent) sectionElement;
				section.add(abstractComponentModeller.createModelFromXml(
						component, locale, sellerMode));
			} else {
				throw new RuntimeException(
						"Unknown component! Cannot create model for xml component of type "
								+ xmlObject.getClass());
			}
		}

		return section;
	}
}
